package view;

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import javax.swing.*;

import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;


import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import javax.swing.table.DefaultTableModel;
import main.WinkelApplication;
import model.Klant;
import model.Product;

public class Payment extends JPanel implements MouseListener, ActionListener {

    private final int verticalPosition = 80;
    private final int scrollPaneHeight = 100;
    private final int formOffset = 30;
    private JTextField tfid;
    private JTextField tfNaam;
    private JTextField tfAddress;
    private JTextField tfPostcode;
    private JTextField tfWoonplaats;
    private JComboBox cmbPayMethod;
    private JTextField tfNote;
    private final String[] payMethods = {"Vooraf per bank", "Onder rembours", "Geen"};
    private JCheckBox nieuweklant;
    private DefaultTableModel model;
    private JButton btnSend;
    private JTable customerTable;
    private JFrame frame;
    private JButton klantadd;
    private int klantnummer;
    
    public Payment() {
        super();
        this.setLayout(null);
        initComponents();
    }

    private void initComponents() {
        addTitle();
        addProductList();
        addForm();
    }

    private void addTitle() {
        JLabel lblTitle1 = new JLabel();
        lblTitle1.setText("Winkelapplicatie");
        lblTitle1.setBounds(20, 20, 150, 20);
        lblTitle1.setFont(WinkelApplication.FONT_16_BOLD);
        lblTitle1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        lblTitle1.addMouseListener(this);
        add(lblTitle1);

        JLabel lblTitle2 = new JLabel();
        lblTitle2.setText("-");
        lblTitle2.setBounds(170, 20, 20, 20);
        lblTitle2.setFont(WinkelApplication.FONT_16_BOLD);
        add(lblTitle2);
        JLabel lblTitle3 = new JLabel();
        lblTitle3.setText("Betaling");
        lblTitle3.setBounds(190, 20, 500, 20);
        lblTitle3.setFont(WinkelApplication.FONT_16_BOLD);
        add(lblTitle3);
    }

    private void addProductList() {
        List<Product> products = WinkelApplication.getBasket().getProducts();

        JLabel lblProductHeader = new JLabel();
        lblProductHeader.setText("Producten");
        lblProductHeader.setBounds(20, 60, 150, 20);
        lblProductHeader.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblProductHeader);

        JLabel lblAmountHeader = new JLabel();
        lblAmountHeader.setText("Aantal");
        lblAmountHeader.setBounds(380, 60, 150, 20);
        lblAmountHeader.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblAmountHeader);

        JLabel lblPriceHeader = new JLabel();
        lblPriceHeader.setText("Prijs");
        lblPriceHeader.setBounds(450, 60, 150, 20);
        lblPriceHeader.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblPriceHeader);

        add(buildPanelWithProducts(products, 20, 80));

        // create total labels
        JLabel lblTotal = new JLabel("Totaal: ");
        lblTotal.setBounds(20, verticalPosition + scrollPaneHeight, 50, 20);
        lblTotal.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblTotal);

        // create total labels
        JLabel lblTotalPrice = new JLabel(WinkelApplication.CURRENCY + 
                WinkelApplication.PRICE_FORMAT.format(WinkelApplication.getBasket().getTotalCosts()));
        lblTotalPrice.setBounds(450, verticalPosition + scrollPaneHeight, 70, 20);
        lblTotalPrice.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblTotalPrice);
    }

    public JScrollPane buildPanelWithProducts(List<Product> product, int x, int y){
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        panel.setPreferredSize(new Dimension(500, (product.size() * 20)));
        
        JScrollPane scrlP = new JScrollPane(panel);
        scrlP.setSize(520, scrollPaneHeight);
        scrlP.setBorder(null);
        scrlP.setLocation(x, y);
        scrlP.getViewport().add(panel);
        
        for(int i = 0; i < product.size(); i++){
            panel.add(getProductItemPanel(product.get(i)));
        }
        
        return scrlP;
    }
    
    public JPanel getProductItemPanel(Product product) {
        JPanel productPanel = new JPanel();
        productPanel.setPreferredSize(new Dimension(500, 20));
        productPanel.setLayout(null);
        
        JLabel lblProduct = new JLabel(product.getName());
        lblProduct.setBounds(0, 0, 360, 20);
        lblProduct.setFont(WinkelApplication.FONT_10_PLAIN);
        productPanel.add(lblProduct);

        JLabel lblAmount = new JLabel(String.valueOf(WinkelApplication.getBasket().getProductAmount(product)));
        lblAmount.setBounds(360, 0, 70, 20);
        lblAmount.setFont(WinkelApplication.FONT_10_PLAIN);
        productPanel.add(lblAmount);

        JLabel lblPrice = new JLabel(WinkelApplication.CURRENCY + 
                WinkelApplication.PRICE_FORMAT.format(product.getPrice()));
        lblPrice.setBounds(430, 0, 70, 20);
        lblPrice.setFont(WinkelApplication.FONT_10_PLAIN);
        productPanel.add(lblPrice);
        
        return productPanel;
    }

    private void addForm() {
        JLabel lblFormTitle = new JLabel("Verzendgegevens");
        lblFormTitle.setBounds(20, verticalPosition + scrollPaneHeight + (formOffset * 2), 150, 20);
        lblFormTitle.setFont(WinkelApplication.FONT_12_BOLD);
        add(lblFormTitle);
        
        JLabel klantid = new JLabel("Klant:");
        klantid.setBounds(20, verticalPosition + scrollPaneHeight + (formOffset * 3), 100, 20);
        klantid.setFont(WinkelApplication.FONT_10_BOLD);
        add(klantid);
        
        klantadd = new JButton("Zoek Klant");
        klantadd.setName("zoek");
        klantadd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                table();
            }
        });
        
        
        
        klantadd.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 3), 130, 20);
        add(klantadd);
        
        nieuweklant = new JCheckBox("Nieuwe klant");
        nieuweklant.setBounds(320, verticalPosition + scrollPaneHeight + (formOffset * 3), 100, 20);
        add(nieuweklant);
        
        nieuweklant.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
       
            if(nieuweklant.isSelected()){
                //tfid.setEditable(false);
                btnSend.setEnabled(false);
                klantadd.setEnabled(false);
                
                tfNaam.setText("");
                tfAddress.setText("");
                tfPostcode.setText("");
                tfWoonplaats.setText("");
                
                tfNaam.setEditable(true);
                tfAddress.setEditable(true);
                tfPostcode.setEditable(true);
                tfWoonplaats.setEditable(true); 
            } else {
                klantadd.setEnabled(true);
                tfNaam.setText("");
                tfAddress.setText("");
                tfPostcode.setText("");
                tfWoonplaats.setText("");
                
                tfNaam.setEditable(false);
                tfAddress.setEditable(false);
                tfPostcode.setEditable(false);
                tfWoonplaats.setEditable(false); 
            }
            
        }
        });
        /*
        tfid = new JTextField(1);
        tfid.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 3), 130, 20);
        tfid.setFont(WinkelApplication.FONT_10_BOLD);
        
        tfid.addKeyListener(new KeyListener() {

          public void keyTyped(KeyEvent e) {
               
          }

            public void keyPressed(KeyEvent e) {
               
            }

            public void keyReleased(KeyEvent e) {
                
                if(tfid.getText().isEmpty()) {
                    tfNaam.setText("");
                    tfAddress.setText("");
                    tfPostcode.setText("");
                    tfWoonplaats.setText("");
                    
                    tfNaam.setEditable(false);
                    tfAddress.setEditable(false);
                    tfPostcode.setEditable(false);
                    tfWoonplaats.setEditable(false); 
                    
                    btnSend.setEnabled(false);
                }
                
                Klant klant = null;    
                try { 
                  
                  Integer s = Integer.valueOf(tfid.getText());
                  klant = WinkelApplication.getQueryManager().getKlant(s);
                 
                  if(klant != null){
                    
                    tfNaam.setText(klant.getNaam());
                    tfAddress.setText(klant.getAdres());
                    tfPostcode.setText(klant.getPostcode());
                    tfWoonplaats.setText(klant.getWoonplaats());
                    
                    tfNaam.setEditable(false);
                    tfAddress.setEditable(false);
                    tfPostcode.setEditable(false);
                    tfWoonplaats.setEditable(false);
                    
                    btnSend.setEnabled(true);
                    
                  } else {
                    tfNaam.setText("#NIET GEVONDEN#");
                    tfAddress.setText("#NIET GEVONDEN#");
                    tfPostcode.setText("#NIET GEVONDEN#");
                    tfWoonplaats.setText("#NIET GEVONDEN#");
                    
                    tfNaam.setEditable(false);
                    tfAddress.setEditable(false);
                    tfPostcode.setEditable(false);
                    tfWoonplaats.setEditable(false); 

                    btnSend.setEnabled(false);

                    
                    btnSend.setEnabled(false);

                  }
                  
                } catch(NumberFormatException exception) {   
                }
             
            }
        });
        add(tfid);
         */
        JLabel lblNaam = new JLabel("Naam:");
        lblNaam.setBounds(20, verticalPosition + scrollPaneHeight + (formOffset * 4), 100, 20);
        lblNaam.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblNaam);

        tfNaam = new JTextField();
        tfNaam.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 4), 130, 20);
        tfNaam.setFont(WinkelApplication.FONT_10_BOLD);
        tfNaam.setEditable(false);
        tfNaam.getDocument().addDocumentListener(listener);
        add(tfNaam);

        JLabel lblPostcode = new JLabel("Postcode:");
        lblPostcode.setBounds(320, verticalPosition + scrollPaneHeight + (formOffset * 4), 100, 20);
        lblPostcode.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblPostcode);

        tfPostcode = new JTextField();
        tfPostcode.setBounds(420, verticalPosition + scrollPaneHeight + (formOffset * 4), 130, 20);
        tfPostcode.setFont(WinkelApplication.FONT_10_BOLD);
        tfPostcode.setEditable(false);
        tfPostcode.getDocument().addDocumentListener(listener);
        add(tfPostcode);

        JLabel lblAddress = new JLabel("Adres:");
        lblAddress.setBounds(20, verticalPosition + scrollPaneHeight + (formOffset * 5), 100, 20);
        lblAddress.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblAddress);

        tfAddress = new JTextField();
        tfAddress.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 5), 130, 20);
        tfAddress.setFont(WinkelApplication.FONT_10_BOLD);
        tfAddress.setEditable(false);
        tfAddress.getDocument().addDocumentListener(listener);
        add(tfAddress);

        JLabel lblWoonplaats = new JLabel("Woonplaats:");
        lblWoonplaats.setBounds(320, verticalPosition + scrollPaneHeight + (formOffset * 5), 100, 20);
        lblWoonplaats.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblWoonplaats);

        tfWoonplaats = new JTextField();
        tfWoonplaats.setBounds(420, verticalPosition + scrollPaneHeight + (formOffset * 5), 130, 20);
        tfWoonplaats.setFont(WinkelApplication.FONT_10_BOLD);
        tfWoonplaats.setEditable(false);
        tfWoonplaats.getDocument().addDocumentListener(listener);
        add(tfWoonplaats);

        JLabel lblPayMethod = new JLabel("Betaalmethode:");
        lblPayMethod.setBounds(20, verticalPosition + scrollPaneHeight + (formOffset * 6), 100, 20);
        lblPayMethod.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblPayMethod);

        cmbPayMethod = new JComboBox(payMethods);
        cmbPayMethod.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 6), 250, 20);
        cmbPayMethod.setFont(WinkelApplication.FONT_10_BOLD);
        add(cmbPayMethod);

        JLabel lblNote = new JLabel("Opmerking:");
        lblNote.setBounds(20, verticalPosition + scrollPaneHeight + (formOffset * 7), 100, 20);
        lblNote.setFont(WinkelApplication.FONT_10_BOLD);
        add(lblNote);

        tfNote = new JTextField();
        tfNote.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 7), 250, 80);
        tfNote.setFont(WinkelApplication.FONT_10_BOLD);
        add(tfNote);

        btnSend = new JButton("Verzend bestelling");
        btnSend.setBounds(500, 500, 150, 20);
        //btnSend.setBounds(120, verticalPosition + scrollPaneHeight + (formOffset * 9), 150, 20);
        btnSend.setFont(WinkelApplication.FONT_10_BOLD);
        btnSend.setName("bestel");
        btnSend.addActionListener(this);
        btnSend.setEnabled(false);
        this.add(btnSend);
    }

    @Override
    public void actionPerformed(ActionEvent event) {

        List<Product> products = WinkelApplication.getBasket().getProducts();
        for(Product x : products) {
            if(x.getVoorraad() < WinkelApplication.getBasket().getProductAmount(x) ){
                JOptionPane.showMessageDialog(null,
                "Er helaas maar " + x.getVoorraad() + " van het product " + x.getName() + " maar u probeerder er " + WinkelApplication.getBasket().getProductAmount(x) + " te bestellen", " Niet genoeg in voorraad",
                JOptionPane.INFORMATION_MESSAGE);  
                return;
            }
        }

        
        JButton label = (JButton) event.getSource();
        
        if(label.getName().equals("zoek")) {
        JFrame frame = new PaymentSearchCustomer();
        frame.setSize(800, 400);
        frame.setLocation(
                (WinkelApplication.FRAME_WIDTH - frame.getWidth()) / 2, 
                (WinkelApplication.FRAME_HEIGHT - frame.getHeight()) / 2
            );
        
        frame.setResizable(false);
        frame.setVisible(true);

        frame.validate();
        frame.repaint();   
        }
        if(label.getName().equals("bestel")) {

        String naam = tfNaam.getText();
        String adres = tfAddress.getText();
        String opmerking = tfNote.getText();
        String postcode = tfPostcode.getText();
        String woonplaats = tfWoonplaats.getText();
        String betaalmethode = (String) cmbPayMethod.getSelectedItem();
        
        if(nieuweklant.isSelected()) WinkelApplication.getQueryManager().addCostumer(new Klant(naam, adres, postcode, woonplaats));

        WinkelApplication.getQueryManager().setOrder(WinkelApplication.getBasket(),
                naam, adres, postcode, woonplaats, opmerking, betaalmethode);

        for(int i = 0; i < products.size(); i++){
             WinkelApplication.getQueryManager().updateProductVoorraad(
                     (WinkelApplication.getBasket().getProductAmount(products.get(i))),
                     products.get(i).getProductId());
        }
        
        WinkelApplication.getBasket().empty();
        WinkelApplication.getInstance().showPanel(new OrderSend());
         }
    }

    @Override
    public void mouseClicked(MouseEvent event) {
        // the user clicked on the title, go back to the first screen
        WinkelApplication.getInstance().showPanel(new view.CategoryList());
    }

    
    
    @Override
    public void mouseEntered(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void mousePressed(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void mouseReleased(MouseEvent event) {
        // Intentionally left blank.
    }

    @Override
    public void mouseExited(MouseEvent event) {
        // Intentionally left blank.
    }
    DocumentListener listener = new DocumentListener() {
        public void changedUpdate(DocumentEvent e) { 
           updateButton();
        }

        public void insertUpdate(DocumentEvent e) {
           updateButton();
        } 

        private void updateButton() {
          boolean naam = tfNaam.getText().isEmpty();
          boolean adres = tfAddress.getText().isEmpty();
          boolean postcode = tfPostcode.getText().isEmpty();
          boolean woonplaats = tfWoonplaats.getText().isEmpty();
               
          if(naam || adres || postcode || woonplaats) {
           btnSend.setEnabled(false);   
          } else {
           btnSend.setEnabled(true);   
          }
           
        }

        public void removeUpdate(DocumentEvent e) {
           updateButton();
        }
     };  
    
   private void table() {
       
       klantadd.setEnabled(false);
       
         frame = new JFrame();
                frame.setSize(800, 400);
                frame.setLocation(
                (WinkelApplication.FRAME_WIDTH - frame.getWidth()) / 2, 
                (WinkelApplication.FRAME_HEIGHT - frame.getHeight()) / 2
                 );
                
         frame.setLayout(new BorderLayout());          
       
        String[] columnames = {"Klant ID","Naam","Adres", "Postcode", "Woonplaats"};
  
        java.util.List<Klant> customers = WinkelApplication.getQueryManager().getCustomers();
        Object[][] data = new Object[customers.size()][];
        
        for (int i = 0; i < customers.size(); i++)
        {
            Klant k = customers.get(i);
            
            data[i] = new Object[] { k.getKlant_id(),k.getNaam(), k.getAdres(), k.getPostcode(),k.getWoonplaats()};
        }
        
        customerTable = new JTable(data, columnames) {
            @Override
            public boolean isCellEditable(int row, int column){  
                return false;  
            }  
        };
        
        //customerTable.setRowHeight(25);
        customerTable.setFont(WinkelApplication.FONT_14_PLAIN);
        customerTable.setFillsViewportHeight(true);
        
        
        JScrollPane scrollpane = new JScrollPane(customerTable);
       
        
        
        customerTable.addMouseListener(new MouseAdapter() {
            @Override
          public void mouseClicked(MouseEvent e) {
           
              JTable target = (JTable)e.getSource();
              int row = customerTable.getSelectedRow();
              //int col = table.getSelectedColumn();
              
              
              Object lastobj = customerTable.getModel().getValueAt(row, 0);
              Integer last = new Integer(lastobj.toString());
              // do some action if appropriate column
              klantnummer =  last;
            
          }
        });
         frame.add(scrollpane, BorderLayout.CENTER);
         
         JLabel testlabel = new JLabel("Selecteer een klant", SwingConstants.CENTER);
         testlabel.setFont(WinkelApplication.computeFontSize(2));
         frame.add(testlabel, BorderLayout.PAGE_START);
         
         JPanel pnlButtonBar = new JPanel();
        pnlButtonBar.setPreferredSize(new Dimension(WinkelApplication.FRAME_WIDTH, 60));
        
        JButton btnEdit = new JButton("Selecteren");
        btnEdit.setPreferredSize(new Dimension(150, 30));
        btnEdit.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
               
                Klant klant = WinkelApplication.getQueryManager().getKlant(klantnummer);
                 
                  if(klant != null){
                    
                    tfNaam.setText(klant.getNaam());
                    tfAddress.setText(klant.getAdres());
                    tfPostcode.setText(klant.getPostcode());
                    tfWoonplaats.setText(klant.getWoonplaats());
                    
                    tfNaam.setEditable(false);
                    tfAddress.setEditable(false);
                    tfPostcode.setEditable(false);
                    tfWoonplaats.setEditable(false);
                    
                    btnSend.setEnabled(true); 
                    
                    frame.setVisible(false);
                    frame.dispose();
                    klantadd.setEnabled(true);
        
                } else {
                      tfNaam.setText("Poepkop");
                  }
               
            
            }
        });
        pnlButtonBar.add(btnEdit);
        
        JButton btnDelete = new JButton("Annuleren");
        btnDelete.setPreferredSize(new Dimension(150, 30));
        btnDelete.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent ae)
            {
                frame.setVisible(false);
                frame.dispose();
                
                klantadd.setEnabled(true);
            }
        });
        pnlButtonBar.add(btnDelete); 
        frame.add(pnlButtonBar, BorderLayout.PAGE_END); 
        
         frame.setResizable(false);
         frame.setVisible(true);
         frame.validate();
         frame.repaint(); 
    }
    
    @Override
    public void paint(Graphics graphics) {
        super.paint(graphics);
        graphics.drawLine(20, 45, 540, 45);		// under H Title
    }
}


